import React, { Component } from 'react';
import { Spin } from 'antd';
import { WeaTools } from 'ecCom';
import Main from './Main';
import EmailUpgrade from './emailUpgrade';

const { callApi } = WeaTools;

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
    };
    this.getUpgradeInfo();
    this.timer = setInterval(() => this.getUpgradeInfo(), 5000);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
    this.timer = null;
  }

  getUpgradeInfo = (params = {}) => {
    callApi('/api/email/base/emailUpgrade', 'GET', params).then((res) => {
      const { completedcount, totalcount } = res;
      if (res.upgrade_status === '1') {
        clearInterval(this.timer);
        this.timer = null;
      }
      let percent = (completedcount / totalcount).toFixed(4);
      percent = Math.round(percent * 10000) / 100;
      res = { ...res, percent };
      this.setState({ ...res, loading: false });
    });
  }

  render() {
    const preCls = 'email-upgrade';
    const { upgrade_status, resultStatus } = this.state;
    return (
      <div className={preCls}>
      {this.state.loading && <div className={`${preCls}-container`}><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@mf5n6y`} size="large" /></div>}
      {
        ((upgrade_status && upgrade_status === '0') || ((upgrade_status && upgrade_status === '1') && resultStatus && resultStatus === '0')) && (
          <EmailUpgrade ecId={`${this && this.props && this.props.ecId || ''}_EmailUpgrade@cbjap6`} {...this.state} />
        )
      }
      {upgrade_status && upgrade_status === '1' && resultStatus != '0' && <Main ecId={`${this && this.props && this.props.ecId || ''}_Main@qgiu4t`} {...this.props} />}
      </div>
    );
  }
}

export default Home;
